package com.farm.util;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 加密工具类
 */
public class MD5Utils {

    private static BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    /**
     * 使用md5的算法进行加密
     */
    public static String md5(String plainText) {
        byte[] secretBytes = null;
        try {
            secretBytes = MessageDigest.getInstance("md5").digest(
                    plainText.getBytes());
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("没有md5这个算法！");
        }// 16进制数字
        String md5code = new BigInteger(1, secretBytes).toString(16);
        // 如果生成数字未满32位，需要前面补0
        for (int i = 0; i < 32 - md5code.length(); i++) {
            md5code = "0" + md5code;
        }
        return md5code;
    }

    /**
     * 使用SpringSecurity的BCryptPasswordEncoder
     *
     * @param password
     */
    public static String BCrypt(String password) {
        String encode = passwordEncoder.encode(password);

        return encode;
    }

    //校验方法
    //第一个参数未加密，第二个参数，加密了
    public static boolean myMatches(String rawPassword,String encodePasswprd){

        return passwordEncoder.matches(rawPassword,encodePasswprd);
    }


    /**
     *测试使用,获取密码加密密文
     */
    public static void main(String[] args) {
        //System.out.println(md5("1234"));

        System.out.println(BCrypt("123456"));

        System.out.println(passwordEncoder.matches("123456","$2a$10$shu9hg0EReY4/qLDLYPFFOc9dDbPcFiMR/tk9Upv12FWepZnMHb8a"));
        //System.out.println(passwordEncoder.matches("$2a$10$njQnzAwEZRfOuokN.sUf8.uMOYUDg8RpDA.3TaBfwmHuA7iybjZSe","123456"));
    }

}